<template>
  <el-dialog
      v-model="visible"
      title="创建新小说"
      width="60%"
      :close-on-click-modal="false"
      :center="false"
      top="5vh"
      class="create-novel-dialog"
      :destroy-on-close="true"
  >
    <div class="novel-content">
      <!-- 标题区域 -->
      <div class="title-section">
        <h2 class="novel-title">开始你的创作之旅</h2>
        <p class="novel-subtitle">填写基本信息后即可发布你的小说</p>
      </div>

      <!-- 表单区域 -->
      <div class="form-section">
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="novel-form"
        >
          <!-- 小说名称 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="小说名称" prop="name">
                <el-input
                    v-model="form.name"
                    placeholder="请输入小说名称,不超过50个字"
                    maxlength="50"
                    show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 类型与标签 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="小说类型" prop="type">
                <el-select
                    v-model="form.type"
                    placeholder="请选择小说类型"
                    filterable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in typeOptions"
                      :key="item.id"
                      :label="item.type"
                      :value="item.type"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="小说标签">
                <div class="tags-container">
                  <div class="tags-display">
                    <el-tag
                        v-for="(tag, index) in tags"
                        :key="index"
                        closable
                        @close="removeTag(index)"
                        class="tag-item"
                    >
                      {{ tag }}
                    </el-tag>
                    <el-input
                        v-if="inputVisible"
                        ref="inputRef"
                        v-model="inputValue"
                        class="tag-input"
                        size="small"
                        placeholder="输入标签后按回车添加"
                        @keyup.enter="handleInputConfirm"
                        @blur="handleInputConfirm"
                    />
                    <el-button
                        v-else
                        class="tag-add-btn"
                        @click="showInput"
                    >
                      + 添加标签
                    </el-button>
                  </div>
                  <p class="tags-hint">最多可添加10个标签,每个标签不超过5个字</p>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 模型选择 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="文本模型" prop="text_model_id">
                <el-select
                    v-model="form.text_model_id"
                    placeholder="请选择文本模型"
                    filterable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in textModelOptions"
                      :key="item.id"
                      :label="item.model"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片模型" prop="img_model_id">
                <el-select
                    v-model="form.img_model_id"
                    placeholder="请选择图片模型"
                    filterable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in imgModelOptions"
                      :key="item.id"
                      :label="item.model"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 提示词模板 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="提示词模板" prop="prompt_id">
                <el-select
                    v-model="form.prompt_id"
                    placeholder="请选择提示词模板"
                    filterable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in promptOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12"></el-col>
          </el-row>

          <!-- 小说描述 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="小说描述">
                <el-input
                    v-model="form.description"
                    type="textarea"
                    :rows="3"
                    placeholder="简要描述你的小说内容"
                    maxlength="500"
                    show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 世界观设定 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="世界观设定">
                <el-input
                    v-model="form.worldview"
                    type="textarea"
                    :rows="4"
                    placeholder="详细描述你的小说世界观设定,包括背景、主要势力、特殊规则等"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 封面与提示词布局优化 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="封面图片">

                  <ImageUpload
                      v-model="form.img"
                      :limit="1"
                      :file-size="5"
                      :file-type="['png','jpg','jpeg','gif','webp']"
                      :is-show-tip="true"
                  />

                <p class="upload-hint">建议尺寸：300x400px，支持 PNG、JPG、JPEG、GIF、WEBP 格式</p>
              </el-form-item>

              <el-form-item label="参考图片">
                <ImageUpload
                    v-model="form.refImg"
                    :limit="1"
                    :file-size="5"
                    :file-type="['png','jpg','jpeg','gif','webp']"
                    :is-show-tip="true"
                />
                <p class="upload-hint">上传参考图片，用于AI生成封面参考</p>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="封面提示词">
                <div class="prompt-container">
                  <el-input
                      v-model="form.prompt"
                      type="textarea"
                      :rows="6"
                      placeholder="描述封面图片的风格、场景、细节等"
                      show-word-limit
                      class="prompt-textarea"
                  />
                  <div class="prompt-buttons">
                    <el-button
                        type="primary"
                        size="small"
                        :loading="optimizing"
                        :disabled="optimizing || optimizingAndGenerating"
                        @click="handleAIOptimize"
                    >
                      <el-icon v-if="!optimizing"><Star /></el-icon>
                      {{ optimizing ? 'AI优化中...' : 'AI优化' }}
                    </el-button>
                    <el-button
                        type="success"
                        size="small"
                        :loading="generating"
                        :disabled="generating || optimizingAndGenerating || !form.prompt"
                        @click="handleGenerateImage"
                    >
                      <el-icon v-if="!generating"><Star /></el-icon>
                      {{ generating ? '生成中...' : (form.refImg ? '生成图片(参考)' : '生成图片') }}
                    </el-button>
                    <el-button
                        type="warning"
                        size="small"
                        :loading="optimizingAndGenerating"
                        :disabled="optimizingAndGenerating || !form.name || !form.text_model_id || !form.img_model_id || !form.prompt_id"
                        @click="handleOptimizeAndGenerate"
                    >
                      <el-icon v-if="!optimizingAndGenerating"><Star /></el-icon>
                      {{ optimizingAndGenerating ? '优化并生成中...' : '优化并生成' }}
                    </el-button>
                  </div>
                </div>
                <p class="prompt-hint">用于AI生成封面图片，描述越详细效果越好</p>
              </el-form-item>

              <el-form-item label="涉及人物">
                <el-input
                    v-model="form.refRole"
                    type="textarea"
                    :rows="4"
                    placeholder="描述小说中的主要人物"
                    maxlength="500"
                    show-word-limit
                />
                <p class="role-hint">描述小说中的主要人物角色</p>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handleSaveDraft" :loading="saving">暂存草稿</el-button>
        <el-button type="primary" @click="handleSaveAndEnter" :loading="saving">
          保存并进入
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star } from '@element-plus/icons-vue'
import { addNovel, optimizePrompt, generateImage, generateImageWithReference } from '@/api/novel/novel'
import { listType } from '@/api/novel/type'
import { listConfig as listModelConfig } from '@/api/model/config'
import { listConfig as listPromptConfig } from '@/api/prompt/config'
import ImageUpload from '@/components/ImageUpload/index.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// 弹窗显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref()
const inputRef = ref()

// 响应式数据 - 与后端 NovelCreate 类字段完全匹配
const form = reactive({
  name: '',           // 对应后端的 name 字段
  type: '',           // 对应后端的 type 字段
  description: '',    // 对应后端的 description 字段
  worldview: '',      // 对应后端的 worldview 字段
  tag: '',            // 对应后端的 tag 字段（字符串形式）
  img: '',            // 对应后端的 img 字段
  prompt: '',         // 对应后端的 prompt 字段
  refRole: '',        // 对应后端的 refRole 字段
  refImg: '',         // 对应后端的 refImg 字段
  prompt_id: null,    // 对应后端的 prompt_id 字段（Long类型）
  text_model_id: null, // 对应后端的 text_model_id 字段（Long类型）
  img_model_id: null  // 对应后端的 img_model_id 字段（Long类型）
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const tags = ref([])  // 用于前端显示的标签数组

// 类型选项
const typeOptions = ref([])

// 文本模型选项
const textModelOptions = ref([])

// 图片模型选项
const imgModelOptions = ref([])

// 提示词选项
const promptOptions = ref([])

// 加载状态
const saving = ref(false)
const optimizing = ref(false)
const generating = ref(false)
const optimizingAndGenerating = ref(false)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入小说名称', trigger: 'blur' },
    { min: 1, max: 50, message: '小说名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择小说类型', trigger: 'change' }
  ]
}

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    loadTypeOptions()
    loadTextModelOptions()
    loadImgModelOptions()
    loadPromptOptions()
    resetForm()
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    type: '',
    description: '',
    worldview: '',
    tag: '',
    img: '',
    prompt: '',
    refRole: '',
    refImg: '',
    prompt_id: null,
    text_model_id: null,
    img_model_id: null
  })
  tags.value = []
  inputVisible.value = false
  inputValue.value = ''
}

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 添加标签
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (tags.value.length >= 10) {
      ElMessage.warning('最多可添加10个标签')
      return
    }
    if (inputValue.value.length > 5) {
      ElMessage.warning('每个标签不超过5个字')
      return
    }
    if (tags.value.includes(inputValue.value)) {
      ElMessage.warning('标签已存在')
      return
    }
    tags.value.push(inputValue.value)
    // 更新 form.tag 字段，用逗号分隔
    form.tag = tags.value.join(',')
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 移除标签
const removeTag = (index) => {
  tags.value.splice(index, 1)
  // 更新 form.tag 字段
  form.tag = tags.value.join(',')
}

// 暂存草稿
const handleSaveDraft = async () => {
  try {
    saving.value = true
    const response = await addNovel(form)
    ElMessage.success('草稿保存成功')
    emit('success', response.data)
    visible.value = false
  } catch (error) {
    ElMessage.error('保存失败，请重试')
    console.error('Save draft error:', error)
  } finally {
    saving.value = false
  }
}

// 保存并进入
const handleSaveAndEnter = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    const response = await addNovel(form)
    ElMessage.success('小说创建成功')
    emit('success', response.data)
    visible.value = false

    // 跳转到小说详情页面
    if (response.data && response.data.id) {
      const router = useRouter()
      router.push(`/novel-detail/${response.data.id}`)
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建失败，请重试')
    }
    console.error('Create novel error:', error)
  } finally {
    saving.value = false
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}

// AI优化封面提示词
const handleAIOptimize = async () => {
  // 检查必填字段
  if (!form.name) {
    ElMessage.warning('请先填写小说名称')
    return
  }
  if (!form.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!form.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }
  if (!form.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    optimizing.value = true
    ElMessage.info('AI正在优化提示词，请耐心等待...')

    // 调用AI优化接口
    const response = await optimizePrompt(form)

    if (response.success) {
      // 更新优化后的提示词
      form.prompt = response.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else {
      ElMessage.error('AI优化失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('AI optimize error:', error)

    // 根据错误类型提供不同的提示
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      ElMessage.error('AI优化超时，请稍后重试。AI模型处理需要较长时间，请耐心等待。')
    } else {
      ElMessage.error('AI优化失败，请重试')
    }
  } finally {
    optimizing.value = false
  }
}

// 优化并生成图片
const handleOptimizeAndGenerate = async () => {
  // 检查必填字段
  if (!form.name) {
    ElMessage.warning('请先填写小说名称')
    return
  }
  if (!form.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!form.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }
  if (!form.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    optimizingAndGenerating.value = true
    ElMessage.info('正在同时优化提示词和生成图片，请耐心等待...')

    // 同时调用优化提示词和生成图片接口
    const [optimizeResponse, generateResponse] = await Promise.allSettled([
      optimizePrompt(form),
      form.refImg
        ? generateImageWithReference(form.img_model_id, form.prompt, form.refImg, null, null)
        : generateImage(form.img_model_id, form.prompt)
    ])

    // 处理优化提示词的结果
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success) {
      form.prompt = optimizeResponse.value.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else if (optimizeResponse.status === 'rejected') {
      console.error('AI optimize error:', optimizeResponse.reason)
      ElMessage.warning('AI优化失败，但图片生成继续进行')
    }

    // 处理生成图片的结果
    if (generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      const imageUrl = generateResponse.value.localUrl
      if (imageUrl) {
        form.img = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else if (generateResponse.status === 'rejected') {
      console.error('Generate image error:', generateResponse.reason)
      ElMessage.error('图片生成失败：' + (generateResponse.reason?.message || '请重试'))
    }

    // 如果两个操作都成功
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success &&
        generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      ElMessage.success('优化提示词和生成图片都成功完成！')
    }

  } catch (error) {
    console.error('Optimize and generate error:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    optimizingAndGenerating.value = false
  }
}

// 生成图片
const handleGenerateImage = async () => {
  // 检查必填字段
  if (!form.prompt) {
    ElMessage.warning('请先填写封面提示词')
    return
  }
  if (!form.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }

  try {
    generating.value = true
    ElMessage.info('正在生成图片，请耐心等待...')

    let response

    // 根据是否有参考图片选择不同的接口
    if (form.refImg) {
      // 有参考图片，调用带参考图片的接口
      console.log('Using reference image:', form.refImg)
      response = await generateImageWithReference(
        form.img_model_id,
        form.prompt,
        form.refImg,
        null, // image2
        null  // image3
      )
    } else {
      // 没有参考图片，调用普通接口
      console.log('No reference image, using normal generation')
      response = await generateImage(form.img_model_id, form.prompt)
    }

    if (response.success) {
      // 更新封面图片 - 优先使用 imageUrl，如果没有则使用 localUrl
      const imageUrl = response.localUrl
      console.log('Generated image response:', response)
      console.log('Selected imageUrl:', imageUrl)

      if (imageUrl) {
        // 确保 URL 是完整的，如果是相对路径则添加 baseUrl

          form.img = imageUrl

        console.log('Final form.img value:', form.img)
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else {
      ElMessage.error('图片生成失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('Generate image error:', error)

    // 根据错误类型提供不同的提示
    if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      ElMessage.error('图片生成超时，请稍后重试。AI模型处理需要较长时间，请耐心等待。')
    } else {
      ElMessage.error('图片生成失败，请重试')
    }
  } finally {
    generating.value = false
  }
}

// 加载类型选项
const loadTypeOptions = async () => {
  try {
    const response = await listType({ pageNum: 1, pageSize: 100 })
    typeOptions.value = response.rows || []
  } catch (error) {
    console.error('Load type options error:', error)
  }
}

// 加载文本模型选项
const loadTextModelOptions = async () => {
  try {
    const response = await listModelConfig({ pageNum: 1, pageSize: 100 })
    textModelOptions.value = response.rows || []
  } catch (error) {
    console.error('Load text model options error:', error)
  }
}

// 加载图片模型选项
const loadImgModelOptions = async () => {
  try {
    const response = await listModelConfig({ pageNum: 1, pageSize: 100 })
    imgModelOptions.value = response.rows || []
  } catch (error) {
    console.error('Load img model options error:', error)
  }
}

// 加载提示词选项
const loadPromptOptions = async () => {
  try {
    const response = await listPromptConfig({ pageNum: 1, pageSize: 100 })
    promptOptions.value = response.rows || []
  } catch (error) {
    console.error('Load prompt options error:', error)
  }
}
</script>

<style lang="scss" scoped>
.create-novel-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%) !important;
    border-radius: 0 0 24px 24px;
    max-height: 80vh;
    overflow-y: auto;
  }

  :deep(.el-dialog) {
    background: white !important;
    border-radius: 24px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.12), 0 8px 25px rgba(0, 0, 0, 0.08) !important;
    border: 1px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    overflow: hidden;
    max-width: 50vw;
    margin: 0 auto;
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    border-bottom: none;
    padding: 20px 24px 16px 24px;
    border-radius: 24px 24px 0 0;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    }
  }

  :deep(.el-dialog__title) {
    color: white !important;
    font-weight: 700;
    font-size: 18px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-dialog__headerbtn) {
    top: 20px;
    right: 24px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(255, 255, 255, 0.2);
      transform: scale(1.1);
    }
  }

  :deep(.el-dialog__close) {
    color: white !important;
    font-size: 16px;
    font-weight: bold;

    &:hover {
      color: white !important;
    }
  }

  // 强制覆盖暗色主题
  :deep(.el-dialog__wrapper) {
    background-color: rgba(0, 0, 0, 0.4) !important;
    backdrop-filter: blur(4px);
  }
}

// 调整弹窗遮罩层背景色
:deep(.el-overlay) {
  background-color: rgba(0, 0, 0, 0.3) !important;
}

// 强制覆盖暗色主题的弹窗样式
:global(.el-dialog) {
  background: white !important;
  color: #333 !important;
}

:global(.el-dialog__body) {
  background: white !important;
  color: #333 !important;
}

:global(.el-dialog__header) {
  background: white !important;
  color: #333 !important;
}

:global(.el-dialog__title) {
  color: #333 !important;
}

.novel-content {
  background: transparent !important;
  color: #333 !important;
  padding: 24px;

  .title-section {
    text-align: center;
    margin-bottom: 24px;
    padding: 16px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    border-radius: 12px;
    border: 1px solid rgba(102, 126, 234, 0.1);

    .novel-title {
      font-size: 24px;
      font-weight: 700;
      color: #333 !important;
      margin: 0 0 8px 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: -0.5px;
    }

    .novel-subtitle {
      font-size: 14px;
      color: #666 !important;
      margin: 0;
      font-weight: 400;
    }
  }

  .form-section {
    .novel-form {
      .el-form-item {
        margin-bottom: 18px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .el-form-item__label {
        font-weight: 600;
        color: #374151 !important;
        font-size: 13px;
        margin-bottom: 6px;
        display: block;
      }

      // 输入框统一样式
      :deep(.el-input__wrapper) {
        background-color: white !important;
        color: #333 !important;
        border-radius: 10px;
        border: 2px solid #e5e7eb;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        padding: 0 14px;
        height: 40px;

        &:hover {
          border-color: #667eea;
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }

        &.is-focus {
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
      }

      :deep(.el-input__inner) {
        color: #333 !important;
        font-size: 13px;
        height: 36px;
        line-height: 36px;

        &::placeholder {
          color: #9ca3af;
          font-size: 13px;
        }
      }

      // 文本域样式
      :deep(.el-textarea__inner) {
        background-color: white !important;
        color: #333 !important;
        border-radius: 10px;
        border: 2px solid #e5e7eb;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        padding: 10px 14px;
        font-size: 13px;
        line-height: 1.5;

        &:hover {
          border-color: #667eea;
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }

        &:focus {
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        &::placeholder {
          color: #9ca3af;
          font-size: 14px;
        }
      }

      // 选择器样式
      :deep(.el-select__wrapper) {
        background-color: white !important;
        color: #333 !important;
        border-radius: 10px;
        border: 2px solid #e5e7eb;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        padding: 0 14px;
        height: 40px;

        &:hover {
          border-color: #667eea;
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }

        &.is-focus {
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
      }

      :deep(.el-select__placeholder) {
        color: #9ca3af;
        font-size: 13px;
      }

      :deep(.el-select__selected-item) {
        color: #333;
        font-size: 13px;
      }
    }
  }
}

.tags-container {
  .tags-display {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: center;
    min-height: 48px;
    padding: 12px 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    background: white;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    }

    .tag-item {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 8px;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 500;
      box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
      }

      :deep(.el-tag__close) {
        color: white;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        margin-left: 6px;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
        }
      }
    }

    .tag-input {
      width: 140px;
      height: 36px;

      :deep(.el-input__wrapper) {
        height: 36px;
        border: none;
        box-shadow: none;
        padding: 0 12px;
        background: transparent;
      }
    }

    .tag-add-btn {
      height: 36px;
      padding: 0 16px;
      border: 2px dashed #d1d5db;
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
      color: #667eea;
      border-radius: 8px;
      font-size: 13px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        border-color: #667eea;
        color: #667eea;
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(102, 126, 234, 0.2);
      }
    }
  }

  .tags-hint {
    color: #6b7280;
    font-size: 13px;
    margin: 12px 0 0 0;
    padding: 8px 12px;
    background: #f8fafc;
    border-radius: 8px;
    border-left: 3px solid #667eea;
  }
}

.image-upload-container {
  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
    height: 200px;
    border-radius: 12px;
    border: 2px dashed #d1d5db;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    transition: all 0.3s ease;

    &:hover {
      border-color: #667eea;
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.15);
    }
  }

  :deep(.el-upload-dragger .el-icon) {
    font-size: 48px;
    color: #667eea;
    margin-bottom: 16px;
  }

  :deep(.el-upload-dragger .el-upload__text) {
    color: #667eea;
    font-size: 16px;
    font-weight: 600;
  }

  :deep(.el-upload-dragger .el-upload__tip) {
    color: #6b7280;
    font-size: 14px;
    margin-top: 8px;
  }

  // 已上传图片的样式
  :deep(.el-upload-list) {
    .el-upload-list__item {
      width: 100%;
      height: 160px;
      border-radius: 10px;
      overflow: hidden;
      border: 2px solid #e5e7eb;
      transition: all 0.3s ease;

      &:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(102, 126, 234, 0.15);
      }

      .el-upload-list__item-thumbnail {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

.upload-hint {
  color: #6b7280;
  font-size: 13px;
  margin: 12px 0 0 0;
  line-height: 1.5;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 3px solid #10b981;
}

.prompt-hint {
  color: #6b7280;
  font-size: 13px;
  margin: 12px 0 0 0;
  line-height: 1.5;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  padding: 12px 16px;
  border-radius: 8px;
  border-left: 3px solid #667eea;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.role-hint {
  color: #6b7280;
  font-size: 13px;
  margin: 12px 0 0 0;
  line-height: 1.5;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.05) 0%, rgba(34, 197, 94, 0.05) 100%);
  padding: 12px 16px;
  border-radius: 8px;
  border-left: 3px solid #10b981;
  border: 1px solid rgba(16, 185, 129, 0.1);
}

// AI优化和生成图片按钮样式
.prompt-container {
  position: relative;

  .prompt-textarea {
    width: 100%;
    padding-bottom: 60px; // 为按钮留出更多空间

    :deep(.el-textarea__inner) {
      min-height: 120px;
      font-size: 13px;
      line-height: 1.5;
      resize: vertical;
    }
  }

  .prompt-buttons {
    position: absolute;
    bottom: 16px;
    right: 16px;
    z-index: 10;
    display: flex;
    gap: 12px;
  }

  .ai-optimize-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    font-size: 13px;
    font-weight: 600;
    padding: 10px 16px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    height: 40px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
    }

    &:active {
      transform: translateY(0);
    }

    .el-icon {
      margin-right: 6px;
      font-size: 14px;
    }
  }

  .ai-generate-btn {
    background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
    border: none;
    color: white;
    font-size: 13px;
    font-weight: 600;
    padding: 10px 16px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    transition: all 0.3s ease;
    height: 40px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(16, 185, 129, 0.4);
    }

    &:active {
      transform: translateY(0);
    }

    .el-icon {
      margin-right: 6px;
      font-size: 14px;
    }
  }
}

.dialog-footer {
  text-align: right;
  padding: 20px 24px 24px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-radius: 0 0 24px 24px;

  .el-button {
    height: 40px;
    padding: 0 20px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    transition: all 0.3s ease;

    &:not(.el-button--primary) {
      background: white;
      border: 2px solid #e5e7eb;
      color: #6b7280;

      &:hover {
        border-color: #667eea;
        color: #667eea;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
      }
    }

    &.el-button--primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      color: white;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
      }
    }
  }
}

// 响应式设计
@media (min-width: 1400px) {
  .create-novel-dialog {
    :deep(.el-dialog) {
      width: 50% !important;
      max-width: 50vw;
    }
  }
}

@media (max-width: 1200px) {
  .create-novel-dialog {
    :deep(.el-dialog) {
      width: 50% !important;
      max-width: 50vw;
    }
  }
}

@media (max-width: 768px) {
  .create-novel-dialog {
    :deep(.el-dialog) {
      width: 90% !important;
      margin: 0 auto;
      border-radius: 20px;
      max-width: 90vw;
    }

    :deep(.el-dialog__body) {
      max-height: 85vh;
    }

    :deep(.el-dialog__header) {
      padding: 20px 24px 16px 24px;
    }

    :deep(.el-dialog__title) {
      font-size: 18px;
    }
  }

  .novel-content {
    padding: 24px;

    .title-section {
      margin-bottom: 24px;
      padding: 20px;

      .novel-title {
        font-size: 24px;
      }

      .novel-subtitle {
        font-size: 14px;
      }
    }

    .form-section {
      .novel-form {
        .el-form-item {
          margin-bottom: 20px;
        }
      }
    }
  }

  .dialog-footer {
    padding: 20px 24px 24px 24px;

    .el-button {
      height: 40px;
      padding: 0 20px;
      font-size: 13px;
    }
  }

  .prompt-container {
    .prompt-buttons {
      position: static;
      margin-top: 12px;
      justify-content: flex-end;

      .ai-optimize-btn,
      .ai-generate-btn {
        height: 36px;
        padding: 8px 14px;
        font-size: 12px;
      }
    }

    .prompt-textarea {
      padding-bottom: 0;

      :deep(.el-textarea__inner) {
        min-height: 120px;
      }
    }
  }

  // 移动端调整图片和提示词布局
  .novel-content {
    .form-section {
      .novel-form {
        .el-row {
          .el-col {
            &:first-child {
              margin-bottom: 20px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .create-novel-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      border-radius: 16px;
      max-width: 95vw;
    }
  }

  .novel-content {
    padding: 20px;

    .title-section {
      padding: 16px;

      .novel-title {
        font-size: 20px;
      }
    }
  }

  .dialog-footer {
    padding: 16px 20px 20px 20px;
    text-align: center;

    .el-button {
      width: 100%;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
